package com.yitao.cms.utils;


import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import java.util.UUID;

/**
 * @Author: wwl
 * @Date: 2019/4/23 15:53
 * @Description:
 */
@Component
public class QRCodeImageUtils {
    @Value("${imgUrlPath}")
    private String path;
    @Autowired
    private UpdateFileUtils updateFileUtils;

    /**
     * 生成包含字符串信息的二维码图片
     *
     * @param content     二维码携带信息
     * @param qrCodeSize  二维码图片大小
     * @param imageFormat 二维码的格式
     * @throws WriterException
     * @throws IOException
     */
    public String createQrCode(String content, int qrCodeSize, String imageFormat) throws WriterException, IOException {

        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }else{
            updateFileUtils.removeDir();

        }
        String imageName = path + UUID.randomUUID() + ".png";
        FileOutputStream fileOutputStream = new FileOutputStream(new File(imageName));
        //设置二维码纠错级别ＭＡＰ
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 矫错级别
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //创建比特矩阵(位矩阵)的QR码编码的字符串
        BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
        // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
        int matrixWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(matrixWidth - 50, matrixWidth - 50, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, matrixWidth, matrixWidth);
        // 使用比特矩阵画并保存图像
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < matrixWidth; i++) {
            for (int j = 0; j < matrixWidth; j++) {
                if (byteMatrix.get(i, j)) {
                    graphics.fillRect(i - 25, j - 25, 1, 1);
                }
            }
        }
        Boolean result = ImageIO.write(image, imageFormat, fileOutputStream);
        if (result) {
            return imageName;
        } else {
            return null;
        }

    }

    /**
     * 读二维码并输出携带的信息
     */


    public static void readQrCode(InputStream inputStream) throws IOException {
        //从输入流中获取字符串信息
        BufferedImage image = ImageIO.read(inputStream);
        //将图像转换为二进制位图源
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        Result result = null;
        try {
            result = reader.decode(bitmap);
        } catch (ReaderException e) {
            e.printStackTrace();
        }
        System.out.println(result.getText());
    }

    /*
     * overlapImage
     * @description：合成二维码和图片为文件
     * @author 李阳
     * @date 2018/12/13
     * @params [backPicPath, code]
     * @return void
     */
    public static final void combineCodeAndPicToFile(String backPicPath, BufferedImage code, String fillPicPath) {
        try {
            BufferedImage big = ImageIO.read(new File(backPicPath));
            BufferedImage small = code;
        /*//合成两个文件时使用
        BufferedImage small = ImageIO.read(new File(fillPicPath));*/
            Graphics2D g = big.createGraphics();

            //二维码或小图在大图的左上角坐标
            int x = (big.getWidth() - small.getWidth() - 50);
            int y = (big.getHeight() - small.getHeight() - 50);
            g.drawImage(small, x, y, small.getWidth(), small.getHeight(), null);
            g.dispose();
            //为了保证大图背景不变色，formatName必须为"png"
            ImageIO.write(big, "png", new File(fillPicPath));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 测试代码
     *
     * @throws WriterException
     */
   /* public static void main(String[] args) throws IOException, WriterException {
        createQrCode(new FileOutputStream(new File("d:\\qrcode133.png")), "WE1231238239128sASDASDSADSDWEWWREWRERWSDFDFSDSDF123123123123213123", 200, "png");
        *//* readQrCode(new FileInputStream(new File("d:\\qrcode123.png")));*//*
        QRCodeImageUtils.combineCodeAndPicToFile("D:/Lighthouse.jpg", ImageIO.read(new File("d:/qrcode133.png")), "d:/qrcode456.jpg");

    }*/
}
